from __future__ import unicode_literals
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from django.shortcuts import render, HttpResponse, Http404,redirect
from blog.models import Article, Comment
from django.db import connection
from datetime import date
from blog.forms import CommentForm, UserInfo
# Create your views here.
def index(request):
    articles = Article.objects.filter()
    articles_is_recommend = Article.objects.filter(is_recommend=True)
    page = request.GET.get('page', 1)
    per_page = 3
    paginator = Paginator(articles, per_page)
    try:
        articles = paginator.page(page)
    except (InvalidPage, EmptyPage, PageNotAnInteger) as ex:
        articles = paginator.page(1)
    kwgs = {
        'articles': articles,
        'articles_is_recommend': articles_is_recommend,
    }
    return render(request, 'index.html', kwgs)


def index2(request):
    return render(request, 'index.html')

def pay(request):
    return render(request, 'pay.html')

def about(request):
    return render(request, 'pay.html')

def blog(request, blog_id):
    form = CommentForm()
    try:
        article = Article.objects.get(id=blog_id)
        comments = Comment.objects.filter(article_id=article.id, pid=None)
        for comment in comments:
            comment.children_comment = Comment.objects.filter(article_id=article.id, pid=comment.id)
    except Exception as ex:
        #raise Http404('not exist')
        return render(request, '404.html')
    kwgs = {
        'article': article,
        'form': form,
        'comment_list': comments,
    }
    return render(request, 'blog.html', kwgs)

def search(request):
    # GET 方法
    s = request.POST.get('s')
    print(s)
    aritcles = Article.objects.filter(desc__contains=s)
    kwgs = { "s": s,
        'keywords': aritcles}
    return render(request, 'search.html', kwgs)

def tag(request, tag_name):
    return render(request, 'tag.html')

def category(request, category_id):
    return render(request, 'category.html')

def archive(request):
    # archive_articles2 = {}
    # # sql = "SELECT DISTINCT id, DATE_FORMAT(date_publish, '%%Y-%%m') as col_date FROM blog_article ORDER BY date_publish"
    # # print(sql)
    # # # raw 查询结果必须包含主键
    # # year_month = Article.objects.raw(sql)
    #
    # # 使用connection查询
    # sql = "SELECT DISTINCT DATE_FORMAT(date_publish, '%Y-%m-%d') as col_date FROM blog_article ORDER BY date_publish"
    # cursor = connection.cursor()
    # cursor.execute(sql)
    # year_months = cursor.fetchall()
    # print(year_months)
    # for year_month in year_months:
    #     print(year_month)
    #     year_month = year_month[0]
    #     sql2 = "SELECT DATE_FORMAT(date_publish, '%d') as col_day FROM blog_article WHERE date_publish like '%{}%' ORDER BY date_publish".format(year_month)
    #     # year = int(year_month.split('-')[0])
    #     # month = int(year_month.split('-')[1])
    #     # articles = Article.objects.filter(date_publish__year=year, date_publish__month=month)
    #     cursor = connection.cursor()
    #     cursor.execute(sql2)
    #     days = cursor.fetchall()
    #     day_articles = {}  # day 空字典
    #     for day in days:
    #         allday = year_month + '-' + day[0]
    #         day_articles[day[0]] = Article.objects.filter(date_publish__startswith=allday)
    #
    #         archive_articles2[year_month] = day_articles  # 空字典追加
    #         print('#' * 4)
    #         # print (archive_articles_day)
    #         print('#' * 4)
    #         print(archive_articles2)
    #         kwgs = {
    #             # "archive_articles":archive_articles,
    #             "archive_articles2": archive_articles2,
    #             # "archive_articles_day":archive_articles_day
    #             }
    #     for item in year_months:
    #         print(item)
    # return render(request, 'archive.html', kwgs)
    archive_articles = {}

    sql = "SELECT DISTINCT DATE_FORMAT(date_publish, '%Y-%m-%d') as col_date FROM blog_article ORDER BY date_publish"
    cursor = connection.cursor()
    cursor.execute(sql)
    year_month_dates = cursor.fetchall()
    print(year_month_dates)
    for year_month_date in year_month_dates:
        print(year_month_date)
        year_month_date = year_month_date[0]

        articles = Article.objects.filter(date_publish__startswith=year_month_date)
        print(articles)
        archive_articles[year_month_date] = articles

        kwgs = {
            "archive_articles": archive_articles
            }
    return render(request, 'archive.html', kwgs)


def comment_post(request):
    form = CommentForm(request.POST)
    article_id = int(request.POST.get("article"))
    pid = int(request.POST.get('comment_parent'))
    if pid == 0:
        comment_pid = None
    else:
        comment_pid = Comment.objects.get(id=pid)
    if form.is_valid():
        comment = Comment.objects.create(username=form.cleaned_data["username"],
                                         email=form.cleaned_data["email"],
                                         content=form.cleaned_data["comment"],
                                         url=form.cleaned_data["url"],
                                         pid=comment_pid,
                                         article_id=article_id,
                                         )
        print(comment)
    else:
        return HttpResponse('error')
    print(form.is_valid())
    # return render(request, 'pay.html')
    return redirect(request.META["HTTP_REFERER"] + "#comments")

def form_test(request):
    if request.method == "GET":
        user_form = UserInfo()
        kwgs = {
            "user_form": user_form
        }
    else:
        user_form = UserInfo(request.POST)
        kwgs = {"user_form": user_form}

        if user_form.is_valid():
            print("OK")
            print(user_form.cleaned_data["email"])
        else:
            error = user_form.errors
            kwgs["errors"] = error

    return render(request, 'form_test.html', kwgs)



